package com.dave.admin.modular.boss.service.impl;

import cn.hutool.core.map.MapUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dave.admin.modular.boss.dto.UserAdminRolePermParam;
import com.dave.admin.modular.boss.dto.UserNode;
import com.dave.admin.modular.boss.entity.RolePermission;
import com.dave.admin.modular.boss.entity.UserAdmin;
import com.dave.admin.modular.boss.entity.UserRole;
import com.dave.admin.modular.boss.mapper.UserRoleMapper;
import com.dave.admin.modular.boss.service.IRolePermissionService;
import com.dave.admin.modular.boss.service.IUserAdminService;
import com.dave.admin.modular.boss.service.IUserRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 后台用户和角色关系表 服务实现类
 * </p>
 *
 * @author Dave
 */
@Service
public class UserRoleServiceImpl extends ServiceImpl<UserRoleMapper, UserRole> implements IUserRoleService {

    @Autowired
    private IUserAdminService iUserAdminService;
    @Autowired
    private IRolePermissionService iRolePermissionService;


    @Override
    public Map treeUser(String roleId) {

        //已获取角色的用户
        List<UserRole> userRoleList = this.list(new QueryWrapper<UserRole>().eq(UserRole.ROLE_ID, roleId));
        List<String> value = userRoleList.stream().map(x -> x.getUserId()).collect(Collectors.toList());

        //全部用户
        List<UserNode> userNodes = new ArrayList<>();
        List<UserAdmin> userAdmins = iUserAdminService.list(new QueryWrapper<UserAdmin>().select(UserAdmin.ID, UserAdmin.NICK_NAME));
        userAdmins.forEach(x -> {
            //拼装节点信息
            UserNode userNode = new UserNode();
            userNode.setId(x.getId());
            userNode.setNickName(x.getNickName());
            userNodes.add(userNode);
        });

        //用户返回参数
        Map result = MapUtil.builder()
                .put("userNode", userNodes)
                .put("value", value)
                .build();
        return result;
    }


    /**
     * 这个有个笔记需要做一下
     * 权限模型分为： 用户  角色  菜单
     * 用户  -关联-  角色
     * 角色  -关联-  菜单
     * <p>
     * 问题： 用户可以拥有多个角色，角色有自己的菜单 会出现相同菜单出现在两个角色内
     * 解决1： 查询语句去重  （我选择这个）
     * 解决2： 见过有大佬再添加了一张  用户 -关联-菜单的表 维护（空间换时间）
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void relationshipUser(UserAdminRolePermParam userAdminRolePermParam) {

        //删除用户和角色的关系
        this.remove(new QueryWrapper<UserRole>().eq(UserRole.ROLE_ID, userAdminRolePermParam.getRoleId()));
        //删除角色与权限的关系
        iRolePermissionService.remove(new QueryWrapper<RolePermission>().eq(RolePermission.ROLE_ID, userAdminRolePermParam.getRoleId()));

        //用户与角色
        List<UserRole> userRoleList = new ArrayList<>();
        userAdminRolePermParam.getUserIds().stream().forEach(userId -> userRoleList.add(coverUserRole(userAdminRolePermParam.getRoleId(), userId)));
        this.saveBatch(userRoleList);

        //角色与权限
        List<RolePermission> rolePermissions = new ArrayList<>();
        userAdminRolePermParam.getPermissionIds().stream().forEach(permissionId -> rolePermissions.add(coverRolePermission(userAdminRolePermParam.getRoleId(), permissionId)));
        iRolePermissionService.saveBatch(rolePermissions);

    }

    private UserRole coverUserRole(String roleId, String userId) {
        UserRole userRole = new UserRole();
        userRole.setRoleId(roleId);
        userRole.setUserId(userId);
        return userRole;
    }

    private RolePermission coverRolePermission(String roleId, String permissionId) {
        return new RolePermission(roleId,permissionId);
    }
}
